package zhoufu.sz.sanxiao_check;

import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.List;

import javax.inject.Inject;

import zhoufu.sz.sanxiao_check.config.Constant;
import zhoufu.sz.sanxiao_check.databinding.ActivityMainBinding;
import zhoufu.sz.sanxiao_check.event.Event;
import zhoufu.sz.sanxiao_check.event.RxBus;
import zhoufu.sz.sanxiao_check.inject.HasComponent;
import zhoufu.sz.sanxiao_check.inject.components.DaggerLoginComponet;
import zhoufu.sz.sanxiao_check.inject.components.LoginComponet;
import zhoufu.sz.sanxiao_check.location.LocationHelper;
import zhoufu.sz.sanxiao_check.models.GrandCountModel;
import zhoufu.sz.sanxiao_check.models.ReseauModel;
import zhoufu.sz.sanxiao_check.models.StreetInfoModel;
import zhoufu.sz.sanxiao_check.presents.MainPresenter;
import zhoufu.sz.sanxiao_check.ui.BaseActivity;
import zhoufu.sz.sanxiao_check.ui.adapter.WangGeAdapter;
import zhoufu.sz.sanxiao_check.ui.basic.AddEmptyPlaceActivity;
import zhoufu.sz.sanxiao_check.ui.basic.BasicMainActivity;
import zhoufu.sz.sanxiao_check.ui.contract.MainContract;
import zhoufu.sz.sanxiao_check.ui.fragment.StreetListFragment;
import zhoufu.sz.sanxiao_check.utils.UIUtils;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener,
        MainContract.View, HasComponent<LoginComponet>, AdapterView.OnItemSelectedListener
{
    @Inject
    MainPresenter _presenter;

    LoginComponet loginComponet;

    private WangGeAdapter mLeftAdapter;

    private WangGeAdapter mRightAdapter;

    private PopupWindow mPopupWindow;

    private ActivityMainBinding _binding;

    private TabFragmentAdapter fragmentAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(R.string.title_main);
        init();
        LocationHelper.getInstance().startLocation(this);
        _presenter.onStart();
    }

    @Override protected void initAfterOnCreate(ViewDataBinding binding)
    {
        _binding = (ActivityMainBinding) binding;
        _binding.spinner1.setOnItemSelectedListener(this);
    }

    private void init()
    {
        mLeftAdapter = new WangGeAdapter(this, null, R.layout.item_textview);
        mRightAdapter = new WangGeAdapter(this, null, R.layout.item_textview);
        fragmentAdapter = new TabFragmentAdapter(getSupportFragmentManager(),
                this);
        _binding.viewpager.setAdapter(fragmentAdapter);//给ViewPager设置适配器
        _binding.tl.setupWithViewPager(_binding.viewpager);//将TabLayout和ViewPager关联起来。
        _binding.tl.setTabMode(TabLayout.MODE_FIXED);
        _binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                ((StreetListFragment)fragmentAdapter.mSparseArray
                        .get(position)).setArags(_presenter.getStatus(),_presenter.getDistrict()+"");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override protected void initInject()
    {
        loginComponet = DaggerLoginComponet.builder()
                .activityModule(getActivityModule())
                .appComponent(getAppComponent()).build();
        loginComponet.inject(this);
        _presenter.bindView(this);
    }


    @Override public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                _navigator.startMainCenterAct(this, Constant.MainType.ACTION_PERSON_CENTER);
                break;
            case R.id.menu_add:
                showFilteringPopUpMenu(item);
                break;
            case R.id.menu_scan:
                _navigator.startScanAct(this);
                break;
            case R.id.menu_search:
                _navigator.startSearchAct(this);
                break;
        }
        return true;
    }

    public void showFilteringPopUpMenu(final MenuItem mitem)
    {
        PopupMenu popup = new PopupMenu(this, findViewById(R.id.menu_add));
        popup.getMenuInflater().inflate(R.menu.popmenu_add, popup.getMenu());
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
        {
            public boolean onMenuItemClick(MenuItem item)
            {
                switch (item.getItemId())
                {
                    case R.id.menu_add_1:
                        _navigator.startBasicMainAct(MainActivity.this, new StreetInfoModel(),
                                BasicMainActivity.class);
                        break;
                    case R.id.menu_add_2:
                        startActivity(new Intent(MainActivity.this, AddEmptyPlaceActivity.class));
                        break;
//                        case R.id.menu_add_3:
//                        startActivity(new Intent(MainActivity.this, AddFiveInOneActivity.class));
//                        break;
                }
                return true;
            }
        });
        popup.show();
    }

    public void onReseauCheck(View view)
    {
        popupShow(view);
    }


    private void popupShow(View view)
    {
        if ( mPopupWindow == null )
        {
            View     view1     = LayoutInflater.from(this).inflate(R.layout.layout_popup, null);
            ListView listView1 = (ListView) view1.findViewById(R.id.mListViewLeft);
            listView1.setOnItemClickListener(this);
            listView1.setAdapter(mLeftAdapter);
            ListView listView2 = (ListView) view1.findViewById(R.id.mListViewRight);
            listView2.setOnItemClickListener(this);
            listView2.setAdapter(mRightAdapter);
            mPopupWindow = new PopupWindow(view1,
                    UIUtils.getScreentWidth(this) - UIUtils.dip2px(100),
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow
                    .setBackgroundDrawable(getResources().getDrawable(R.drawable.regist_bg_circle));
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.showAsDropDown(view);
        } else
        {
            mPopupWindow.showAsDropDown(view);
        }
    }

    @Override protected int setIndividualId()
    {
        return R.layout.activity_main;
    }

    @Override protected void onDestroy()
    {
        super.onDestroy();
        _presenter.onDestroy();
        LocationHelper.getInstance().stopLocation();
    }

    @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        switch (parent.getId())
        {
            case R.id.mListViewLeft:
                _presenter.checkLeft(position);
                break;
            case R.id.mListViewRight:
                ReseauModel model = _presenter.checkRight(position);
                _binding.mTvReseau.setText(model.getSuperName() +"--"+ model.getName());
                mPopupWindow.dismiss();
                RxBus.getDefault()
                        .post(new Event.RefreshStreetStatuEvent(_presenter.getStatus(),
                                _presenter.getDistrict()));
                break;
        }
    }

    @Override public void setLeftAdapter(List<ReseauModel> list)
    {
        mLeftAdapter.replaceAll(list);
    }

    @Override public void setRightAdapter(List<ReseauModel> list)
    {
        mRightAdapter.replaceAll(list);
    }

    @Override public void setTabData(GrandCountModel model)
    {
        for (int i = 0; i < _binding.tl.getTabCount(); i++)
        {
            TabLayout.Tab tab = _binding.tl.getTabAt(i);
            switch (i)
            {
                case 0:
                    tab.setCustomView(
                            fragmentAdapter.getTabView(0, "0", _presenter.getDistrictName()));
                    break;
                case 1:
                    tab.setCustomView(fragmentAdapter.getTabView(1,
                            TextUtils.isEmpty(model.getGradeA()) ? "0" : model.getGradeA(), ""));
                    break;
                case 2:
                    tab.setCustomView(fragmentAdapter.getTabView(2,
                            TextUtils.isEmpty(model.getGradeB()) ? "0" : model.getGradeB(), ""));
                    break;
                case 3:
                    tab.setCustomView(fragmentAdapter.getTabView(3,
                            TextUtils.isEmpty(model.getGradeC()) ? "0" : model.getGradeC(), ""));
                    break;
                default:
                    break;
            }
        }
    }

    @Override public void showToast(String msg)
    {
        UIUtils.showSnackbar(toolbar.getRootView(), msg);
    }

    @Override public void pullFaild()
    {

    }

    @Override public void pullEnd()
    {

    }

    @Override public void pullStart()
    {

    }

    @Override public LoginComponet getComponent()
    {
        return loginComponet;
    }

    @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        TextView v1 = (TextView) view;
        if ( v1 == null )
        {
            return;
        }
        v1.setTextColor(Color.BLACK);
        _presenter.setStatus(position);
        _presenter.gradeData(null);
        RxBus.getDefault()
                .post(new Event.RefreshStreetStatuEvent(position, _presenter.getDistrict() + ""));
    }

    @Override public void onNothingSelected(AdapterView<?> parent)
    {

    }

    public static class TabFragmentAdapter extends FragmentPagerAdapter
    {

        SparseArray<Fragment> mSparseArray;

        MainActivity context;

        private int imageResId[] = {
                R.drawable.shape_oval_backpage_gray,
                R.drawable.shape_oval_backpage_green,
                R.drawable.shape_oval_backpage_yellow,
                R.drawable.shape_oval_backpage_red
        };

        SparseArray<View> mViewSparseArray;

        private String[] arrstr;

        public TabFragmentAdapter(FragmentManager fm, MainActivity context)
        {
            super(fm);
            init();
            this.context = context;
            arrstr = context.getResources().getStringArray(R.array.main_tab);
        }

        private void init()
        {
            mSparseArray = new SparseArray();
            mViewSparseArray = new SparseArray<>(4);
        }

        @Override
        public int getCount()
        {
            return imageResId.length;
        }


        @Override
        public CharSequence getPageTitle(int position)
        {
            return null;
        }

        public View getTabView(int position, String count, String girdName)
        {
            View view;
            if ( mViewSparseArray.indexOfKey(position) > -1 )
            {
                view = mViewSparseArray.get(position);
            } else
            {
                view = LayoutInflater.from(context).inflate(R.layout.layout_tab_item, null);
                mViewSparseArray.put(position, view);
            }
            TextView tv  = (TextView) view.findViewById(R.id.textView);
            TextView img = (TextView) view.findViewById(R.id.imageView);
            img.setBackgroundResource(imageResId[position]);
            if ( position == 0 )
            {
                img.setVisibility(View.GONE);
                tv.setText(girdName);
            } else
            {
                img.setVisibility(View.VISIBLE);
                tv.setText(count + "家");
                img.setText(arrstr[position - 1]);
            }
            return view;
        }


        @Override
        public Fragment getItem(int position)
        {
            if ( mSparseArray.indexOfKey(position) > 0 )
            {
//                ((StreetListFragment)mSparseArray.get(position)).setArags(context._presenter.getStatus(), "0",
//                        context._presenter.getDistrict() + "");
            } else
            {
                switch (position)
                {
                    case 0:
                        mSparseArray.put(position, StreetListFragment
                                .newInstance(context._presenter.getStatus(), "0",
                                        context._presenter.getDistrict() + ""));
                        break;
                    case 1:
                        mSparseArray.put(position, StreetListFragment
                                .newInstance(context._presenter.getStatus(), "A",
                                        context._presenter.getDistrict() + ""));
                        break;
                    case 2:
                        mSparseArray.put(position, StreetListFragment
                                .newInstance(context._presenter.getStatus(), "B",
                                        context._presenter.getDistrict() + ""));
                        break;
                    case 3:
                        mSparseArray.put(position, StreetListFragment
                                .newInstance(context._presenter.getStatus(), "C",
                                        context._presenter.getDistrict() + ""));
                        break;
                }
            }
            return mSparseArray.get(position);
        }
    }
}
